-- 取消订单还原购买数量等传入的数据格式,对于redis来说,lua是原子性的,有事务的

-- 检验库存信息 这里的key是
local cachePrefix = KEYS[1]
local orderNumber = KEYS[2]
local activityId = KEYS[3]
local prodCount = tonumber(KEYS[4])
local userId = KEYS[5]
local skuId = KEYS[6]
local pointId = KEYS[7]
local boughtNum = 0


-- 删除订单锁定记录,还原库存（订单未支付前取消订单）
local isDelete = redis.call('del', cachePrefix.."lock:"..orderNumber)
-- 删除锁定标记成功才进行还原购买数量，让方法幂等
if isDelete > 0 then
    -- 如果有限购，则用户已购数量回退
    if (redis.call('exists', cachePrefix.."buy:"..activityId.."_"..userId) == 1) then
        -- 用户已购数量
        boughtNum = redis.call('get', cachePrefix.."buy:"..activityId.."_"..userId)
        redis.call('set',cachePrefix.."buy:"..activityId.."_"..userId, boughtNum - prodCount)
    end
    -- 库存回退
    if prodCount ~= 0 then
        -- 下面通过get获取当前的库存数量
        -- multiDecrementBO.getCachePrefix() + STOCK + multiDecrementBO.getActivityId() + StrUtil.C_UNDERLINE + multiDecrementBO.getSkuId()
        local stock = tonumber(redis.call('get', cachePrefix.."stock:"..activityId.."_"..skuId))
        local pointStock = tonumber(redis.call('get', cachePrefix.."stock:"..activityId.."_"..skuId.."_"..pointId))
        redis.call('set',cachePrefix.."stock:"..activityId.."_"..skuId, tostring(stock + prodCount))
        redis.call('set',cachePrefix.."stock:"..activityId.."_"..skuId.."_"..pointId, tostring(pointStock + prodCount))
    end
end

